package net.xuele.learn.flink.utils;

import net.xuele.learn.IO.bio.TimeServerHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

/**
 * 缺点在于：每当有一个新的客户端请求接入的时候，服务端必须再起一个线程处理新接入的客户端连接。浪费资源！！！
 */
public class SimpleServer {
    public static void main(String[] args) throws IOException {
        int port = 9999;
        ServerSocket serverSocket = null;
        try {
            // 这一步调用了bind函数和listen函数
            serverSocket = new ServerSocket(port);
            System.out.println("the server start at port" + port);
            Socket socket = serverSocket.accept();
            Scanner scanner = new Scanner(System.in);
            // 接收到连接，就进行具体业务的处理，也就是读取发送过来的消息
            PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
            while (scanner.hasNext()) {
                String next = scanner.next();
                System.out.println(next);
                pw.write(next);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                System.out.println("the server is closed!");
                serverSocket.close();
            }
        }

    }

    private static class SimpleHandler implements Runnable {

        private Socket socket;

        public SimpleHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            PrintWriter pw = null;
            try {
                pw = new PrintWriter(this.socket.getOutputStream(), true);
                while (true) {
                    // 读取客户端发来的消息！！！

                    // 输出流，发送给客户端
                    pw.println();
                }
            } catch (Exception e) {
                if (pw != null) {
                    pw.close();
                }
                if (this.socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                this.socket = null;
            }
        }
    }
}
